package com.wuyan.web.base.helper;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 网络相关
 */

@Slf4j
public class NetHelper {
    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     *
     * @return ip
     */
    public static String getRealIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    /**
     * 获取请求头中的IP地址
     *
     * @param request 请求体
     * @return String
     */
    public static String getIpAddr(HttpServletRequest request) throws UnknownHostException {
        String ipAddress = null;
        ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if (ipAddress.equals("127.0.0.1")) {
                // 根据网卡取本机配置的IP
                InetAddress inet;
                inet = InetAddress.getLocalHost();

                assert inet != null;
                ipAddress = inet.getHostAddress();
            }
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
            // = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }

        return ipAddress;
    }

    /**
     * 获取本机外网V4 IP地址
     *
     * @return String
     */
    public static String getLocalV4IP() throws IOException {
        String ip = "";
        String chinaz = "http://ip.chinaz.com/";

        StringBuilder inputLine = new StringBuilder();
        String read = "";
        URL url = null;
        HttpURLConnection urlConnection = null;
        BufferedReader in = null;
        url = new URL(chinaz);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), StandardCharsets.UTF_8));
        while ((read = in.readLine()) != null) {
            inputLine.append(read).append("\r\n");
        }

        in.close();

        Pattern p = Pattern.compile("<dd class=\"fz24\">(.*?)</dd>");
        Matcher m = p.matcher(inputLine.toString());
        if (m.find()) {
            ip = m.group(1);
        }

        return ip;
    }

    /**
     * 获取某一个URL对应的服务器IP地址
     *
     * @param strUrl URL
     * @return String
     */
    public static String getWebIp(String strUrl) throws IOException {
        if (strUrl == null) {
            strUrl = "http://www.zgllh.site";
        }

        URL url = new URL(strUrl);
        BufferedReader br = new BufferedReader(new InputStreamReader(
                url.openStream()));
        String s;
        StringBuilder sb = new StringBuilder("");
        String webContent = "";
        while ((s = br.readLine()) != null) {
            sb.append(s).append("rn");
        }
        br.close();

        webContent = sb.toString();
        int start = webContent.indexOf("[") + 1;
        int end = webContent.indexOf("]");
        if (end < 0) {
            return null;
        }

        webContent = webContent.substring(start, end);
        return webContent;
    }

    /**
     * 将ip地址转换为Long型，二进制
     *
     * @param ip ip地址
     * @return Long
     */
    public static Long ipToLong(String ip) {
        if (ip == null) {
            return -1L;
        }

        if (ip.equals("0:0:0:0:0:0:0:1")) {
            return 0L;
        }

        if (ip.length() < 7) {
            return -1L;
        }

        // IPV4
        if (ip.length() < 16) {
            String[] split = ip.split("\\.");
            if (split.length != 4) {
                return -1L;
            }

            return Long.parseLong(split[0]) << 24 | Long.parseLong(split[1]) << 16 | Long.parseLong(split[2]) << 8 | Long.parseLong(split[3]);
        }

        // IPV6
        return 1L;
    }

}
